package com.service.mybatis.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.model.pojo.DelFlag;
import com.service.mybatis.pojo.BasicEntity;
import com.service.mybatis.pojo.FlagEntity;
import com.service.mybatis.pojo.SuperEntity;
import com.service.mybatis.service.ISuperFlagService;
import com.service.mybatis.service.ISuperService;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * service实现父类
 * 提取一个中间层
 * @author ccf
 */
public class SuperFlagServiceImpl<M extends BaseMapper<T>, T extends FlagEntity> extends SuperServiceImpl<M, T> implements ISuperFlagService<T> {

    @Override
    public boolean isExistNameAndDelFlag(String id, String fieldValue) {
        return isExistFieldAndDelFlag(id, fieldValue, NAME);
    }

    @Override
    public boolean isExistFieldAndDelFlag(String id, String fieldValue, String fieldName) {
        if (StrUtil.isEmpty(fieldValue)){
            return false;
        }
        Map<String, Object> map = new HashMap<>();
        map.put(fieldName, fieldValue);
        map.put(DEL_FLAG, DelFlag.EXIST.getCodeStr());
        List<T> ts = baseMapper.selectByMap(map);
        if (ts.size() == 0){
            return false;
        } else if(ts.size() == 1 && StrUtil.isNotBlank(id) ){
            T t = ts.get(0);
            if (id.equals(t.getId())){
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    @Override
    public void logicRemoveByIds(String... ids) {
        List<T> oldData = baseMapper.selectBatchIds(Arrays.stream(ids).collect(Collectors.toList()));
        if (CollUtil.isNotEmpty(oldData)){
            oldData.stream().forEach(e->e.setDelFlag(DelFlag.NOT_EXIST.getCode()));
            saveOrUpdateBatch(oldData);
        }
    }

}
